package com.shou.zhnfyxt.filter;

import com.alibaba.fastjson.JSONObject;
import com.shou.zhnfyxt.entity.Error;
import com.shou.zhnfyxt.entity.R;
import com.shou.zhnfyxt.utils.RedisCache;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  Filter链 异常捕获 处理
 */
@Component
@Slf4j
public class ExceptionHandlerFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;
    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (ExpiredJwtException e) {
            R<Integer> r = R.error(Error.TOKEN_EXPIRED);
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
            response.setHeader("Content-Type","application/json");
            response.getWriter().write(JSONObject.toJSON(r).toString());
            String userId = e.getClaims().getSubject();
            boolean b = redisCache.deleteObject("login:" + userId);
            if (b){
                System.out.println("redis删除成功");
            }
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
}
